package edu.mti.csi.amaml.script;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import edu.mti.csi.amaml.xml.XSLTTransformer;

/**
 * Generates the Java code of the system diagram XML documents.
 *
 */
public class SystemGenerator
{
	/**
	 * Path of the XSLT stylesheet.
	 */
	private String xsltPath;
	
	/**
	 * Path of the system diagram XML document.
	 */
	private String xmlPath;
	
	/**
	 * Name of the agent whose Java code will be generated.
	 */
	private String agentName;
	
	/**
	 * Path of the folder containing the Java code.
	 */
	private String javaFolderPath;
	
	/**
	 * Validates the script parameters.
	 * @param args Parameters of the script.
	 * @return True if parameters are valid.
	 */
	public boolean validateParameters(String[] args)
	{
		boolean valid = false;
		
		if (args.length == 5)
		{
			if (args[2].equals("-a"))
			{
				this.xsltPath = args[0];
				this.xmlPath = args[1];
				this.agentName = args[3];
				this.javaFolderPath = args[4];
				
				valid = true;
			}
		}
		
		return valid;
	}
	
	/**
	 * Generates the system output.
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 * @throws TransformerException 
	 * @throws FileNotFoundException 
	 */
	public void generateSystem() throws FileNotFoundException, TransformerException, SAXException, IOException, ParserConfigurationException
	{
		String[][] params = new String[1][];
		params[0] = new String[2];
		params[0][0] = "agent_name";
		params[0][1] = agentName;
		
		XSLTTransformer.transform(xmlPath, xsltPath, params, javaFolderPath + "/" + agentName + ".java");
	}
	
	/**
	 * @param args Script arguments:
	 * xslt_file: Path of the system diagram XSLT stylesheet.
	 * xml_file: Path of the system diagram XML document.
	 * -a agent_name: Name of the agent whose Java code will be generated.
	 * output_folder: Path of the folder containing the Java code.
	 */
	public static void main(String[] args)
	{
		SystemGenerator sg = new SystemGenerator();
		
		if(sg.validateParameters(args))
		{
			try
			{
				sg.generateSystem();
			}
			catch (Exception e)
			{
				System.err.println("Unexpected error: " + e.getMessage());
			}
		}
		else
		{
			System.out.println("SINTAX: systemgenerator xslt_file xml_file -a agent_name output_folder");
			System.out.println("	- xslt_file: Path of the system diagram XSLT stylesheet");
			System.out.println("	- xml_file: Path of the system diagram XML document");
			System.out.println("	- agent_name: Name of the agent whose Java code will be generated");
			System.out.println("	- output_folder: Path of the folder containing the Java code");
		}
	}
}
